<?php
declare (strict_types = 1);

namespace app\api\controller\v1;

use app\api\controller\Base;
use app\api\model\ProjectLevel;
use app\api\model\ProjectPerOrgPeople as ProjectPerOrgPeopleModel;
use app\api\model\ProjectReviewResult as ProjectReviewResultModel;
use app\api\model\ProjectPerOrg as ProjectPerOrgModel;
use app\api\model\ProjectInfo as ProjectInfoModel;
use app\api\model\ProjectTeaminfo as ProjectTeaminfoModel;
use app\api\model\ProjectTeamScore as ProjectTeamScoreModel;
use app\api\model\ProjectPerformanceClass as ProjectPerformanceClassModel;
use app\api\model\ProjectPerformanceSpot as ProjectPerformanceSpotModel;

use app\api\model\ProjectLockPerOrgPeople as ProjectLockPerOrgPeopleModel;
use app\api\model\ProjectLockPerOrg as ProjectLockPerOrgModel;
use app\api\model\ProjectLockReviewResult as ProjectLockReviewResultModel;
use app\api\model\ProjectLockPerformanceClass as ProjectLockPerformanceClassModel;
//use app\api\model\ProjectLockPerformanceContent as ProjectLockPerformanceContentModel;
use app\api\model\ProjectLockPerformanceSpot as ProjectLockPerformanceSpotModel;
use app\api\model\ProjectUserRoute as ProjectUserRouteModel;

use app\Request;

class PerOrgPeople extends Base
{

    /**
     * 考核组织人员列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function peopleList(Request $request)
    {
        try {
            $orgid = $request->param('orgid');
            $page = $request->param('page');
            $pagesize = $request->param('pagesize');
            $ProjectPerOrgPeopleModel = new ProjectPerOrgPeopleModel;
            $list = $ProjectPerOrgPeopleModel->alias('p')
                ->field('p.id,p.uid,p.orgid,o.orgname,p.name,p.kp,p.mark,p.status,c.name as kp_name,p.is_outer,p.is_reiviewed')
                ->leftjoin('ProjectPerformanceClass c','p.kp = c.id')
                ->leftjoin('ProjectPerOrg o','p.orgid = o.id')
                ->where('p.orgid','=',$orgid)
                ->paginate([
                    'list_rows'=> $pagesize,
                    'var_page' => 'page',
                    'page'=>$page
                ]);
            if($list){
                $result = ["status"=>true,"msg"=>"获取列表成功！","data"=>$list];
            }else{
                $result = ["status"=>false,"msg"=>"获取列表失败！"];
            }
            return json($result);

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    public function peopleListTj(Request $request){
        try {

            $uid = $request->param('uid');
            //临时加上的管理员判断
            $ProjectPerOrgPeopleModel = new ProjectPerOrgPeopleModel();
            $t = $ProjectPerOrgPeopleModel->where('id','=',$uid)->find();
            $ProjectUserRouteModel = new ProjectUserRouteModel();
            $tt = $ProjectUserRouteModel->where('uid','=',$t['id'])->find();
            if(!$tt){
              $result = ['status'=>false,'msg'=>'暂无数据！'];
              return json($result);
            }
            //临时加上的管理员判断

            $month = strtotime($request->param('month'));
            //查询该用户是否有权限
            $ProjectPerOrgPeopleModel = new ProjectLockPerOrgPeopleModel();
            $userinfo =  $ProjectPerOrgPeopleModel->where('id',$uid)->find();
            if(!$userinfo['is_counter']){
                //$result = ["status"=>false,"msg"=>"无权限！"];
                //return json($result);
            }

            $orgid = $request->param('orgid');
            $ProjectLockPerOrgModel = new ProjectLockPerOrgModel;
            $orginfo_tmp_count = $ProjectLockPerOrgModel->where('id','=',$orgid)
                ->where('pid','=',0)->where('month','like',$month)->count();
            if(!$orginfo_tmp_count){
                $ProjectLockPerOrgModel = new ProjectPerOrgModel;
                $orginfo_tmp = $ProjectLockPerOrgModel->where('id','=',$orgid)
                    ->where('pid','=',0)->find();
            }else{
                $orginfo_tmp = $ProjectLockPerOrgModel->where('id','=',$orgid)
                    ->where('pid','=',0)->where('month','like',$month)->find();
            }



            if($orginfo_tmp){
                $result = ['status'=>false,'msg'=>'获取数据失败！'];
                return json($result);
            }

            $this->scoresortIteraction($ProjectLockPerOrgModel,$orgid,$orginfo_tmp_count,$month);
            global $score_orgid;
            $final_orgid = $score_orgid;

            //根据顶级组织id获取下级组织id
            $ProjectLockPerOrgModel = new ProjectLockPerOrgModel();
            $orgLock_count = $ProjectLockPerOrgModel->where('month','like',$month)->count();
            if(!$orgLock_count) $ProjectLockPerOrgModel = new ProjectPerOrgModel();

            if($userinfo){
                $userinfo = $userinfo->toArray();
            }
            $this->findOrglistIteraction($ProjectLockPerOrgModel,$final_orgid,$orgLock_count,$month);
            //$this->findOrglistIteraction($ProjectPerOrgModel,$userinfo['orgid']);
            global  $org_global;
            $orglist = $org_global;
            //构造查询字符串
            $orgArr = "{$final_orgid}";
            //$orgArr = "{$final_orgid}";
            $orgArr = "";
            if($orglist){
                foreach ($orglist as $o){
                    $orgArr = $orgArr.",".$o['id'];
                }
            }

            //根据这些部门去查询评分记录并汇总
            $ProjectReviewResultModel = new ProjectLockReviewResultModel();
            $ProjectPerformanceClassModel = new ProjectLockPerformanceClassModel;
            $ProjectPerformanceSpotModel = new ProjectLockPerformanceSpotModel;

            $p1 = $ProjectReviewResultModel->where('month','like',$month)->count();
            $p2 = $ProjectPerformanceClassModel->where('month','like',$month)->count();
            $p3 = $ProjectPerformanceSpotModel->where('month','like',$month)->count();
            if(!$p1) $ProjectReviewResultModel = new ProjectReviewResultModel();
            if(!$p2) $ProjectPerformanceClassModel = new ProjectPerformanceClassModel();
            if(!$p3) $ProjectPerformanceSpotModel = new ProjectPerformanceSpotModel();

            $weight_quality = $ProjectPerformanceClassModel->where('id','=',2)->find()->toArray(); //取质量分类得权重
            $spot_quality = $ProjectPerformanceSpotModel->where('weight','>',0)->select();//取考核标准得权重，有权重值的，按照权重值算出来的分数，加到总分里边
            $spot_quality_arr = "";
            foreach ($spot_quality as $v){
                $spot_quality_arr = $spot_quality_arr.$v['id'].',';
            }
            $spot_quality_arr = rtrim($spot_quality_arr, ",");
            $reviewResultList_quality = $ProjectReviewResultModel->alias('rw')
                ->field('p.name,rw.uid,((sum(rw.score*100)/100+100)*'.($weight_quality["weight"]/100).') as total_score')
                ->join('ProjectPerOrgPeople p','rw.uid = p.id')
                ->where('org_id','IN',$orgArr)
                ->where('rw.month','=',$month)
                ->where('spot_id','NOT IN',"$spot_quality_arr")
                ->where('class_id','=',2)
                ->group('rw.uid')
                ->select()->toArray(); //不包括考核标准设置了权重值的

            $reviewResultList_weight_quality= $ProjectReviewResultModel->alias('rw')
                ->field('p.name,rw.uid,(sum(rw.score*100*(weight/100))/100) as total_score')
                ->join('ProjectPerOrgPeople p','rw.uid = p.id')
                ->join('project_performance_spot s','rw.spot_id = s.id')
                ->where('org_id','IN',$orgArr)
                ->where('rw.month','=',$month)
                ->where('spot_id','IN',"$spot_quality_arr")
                ->where('rw.class_id','=',2)
                ->group('rw.uid')
                ->select()->toArray(); //只包含考核标准设置了权重值的

            $weight_normal = $ProjectPerformanceClassModel->where('id','=',1)->find()->toArray();
            $reviewResultList_normal = $ProjectReviewResultModel->alias('rw')
                ->field('p.name,rw.uid,(sum(rw.score*100)*'.($weight_normal["weight"]/100).'/100) as total_score')
                ->join('ProjectPerOrgPeople p','rw.uid = p.id')
                ->where('org_id','IN',$orgArr)
                ->where('rw.month','=',$month)
                ->where('class_id','=',1)
                ->group('rw.uid')
                ->select()->toArray(); //不包括考核标准设置了权重值的

            if($reviewResultList_normal){

                //把质量分加入到日常分里去
                $i=0;
                foreach($reviewResultList_normal as $key=>$vo){

                    foreach ($reviewResultList_quality as $k=>$v){
                        if($v['uid'] == $vo['uid']){
                            $reviewResultList_normal[$i]['total_score'] = $reviewResultList_normal[$i]['total_score']+$v['total_score'];
                        }
                    }
                    $i++;

                }

                //把附加分加进去
                $i=0;
                foreach($reviewResultList_normal as $key=>$vo){

                    foreach ($reviewResultList_weight_quality as $k=>$v){
                        if($v['uid'] == $vo['uid']){
                            $reviewResultList_normal[$i]['total_score'] = $reviewResultList_normal[$i]['total_score']+$v['total_score'];
                        }
                    }
                    $i++;

                }


            }

            if($reviewResultList_normal){
                $reviewResultList_normal_result = arraySort($reviewResultList_normal, 'total_score', SORT_DESC);
                $result = ['status'=>true,'msg'=>'获取数据成功！','data'=>$reviewResultList_normal_result];
                return json($result);
            }else{
                $result = ['status'=>false,'msg'=>'无考核单数据！'];
                return json($result);
            }


        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }
    /**
     * 添加考核组织人员
     * @param Request $request
     * @return \think\response\Json
     */
    public function addPeople(Request $request){
        try {
            $data['orgid'] = $request->param('orgid');
            $data['name'] = $request->param('name');
            $data['kp'] = $request->param('kp');
            $data['is_outer'] = $request->param('is_outer');
            $data['uid'] = $request->param('uid');
            $data['is_reiviewed'] = $request->param('is_reiviewed');
            $data['status'] = 1;
            $data['create_time'] = time();

            $ProjectPerOrgPeopleModel = new ProjectPerOrgPeopleModel();
            $res = $ProjectPerOrgPeopleModel->insertGetId($data);
            if($res){
                $result = ["status"=>true,"msg"=>"添加成功！"];
            }else{
                $result = ["status"=>false,"msg"=>"添加失败！"];
            }
            return json($result);

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    /**
     * 编辑考核组织人员
     * @param Request $request
     * @return \think\response\Json
     */
    public function savePeople(Request $request){
        try {
            $id = $request->param('id');
            if($request->param('orgid'))  $data['orgid'] = $request->param('orgid');
            if($request->param('name'))  $data['name'] = $request->param('name');
            $data['uid'] = $request->param('uid');
            $data['is_outer'] = $request->param('is_outer');
            $data['is_reiviewed'] = $request->param('is_reiviewed');
            $data['kp'] = $request->param('kp');
            $data['update_time'] = time();

            $ProjectPerOrgPeopleModel = new ProjectPerOrgPeopleModel();
            $res = $ProjectPerOrgPeopleModel->where('id','=',$id)->save($data);

            if($res !== false){
                $result = ["status"=>true,"msg"=>"编辑成功！"];
            }else{
                $result = ["status"=>false,"msg"=>"编辑失败！"];
            }
            return json($result);

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    /**
     * 删除考核组织人员
     * @param Request $request
     * @return \think\response\Json
     */
    public function delPeople(Request $request){
        try {

            $id = $request->param('id');
            $ProjectPerOrgPeopleModel = new ProjectPerOrgPeopleModel();
            $res = $ProjectPerOrgPeopleModel->where('id','=',$id)->delete();
            if($res){
                $result = ["status"=>true,"msg"=>"删除成功！"];
            }else{
                $result = ["status"=>false,"msg"=>"删除失败！"];
            }
            return json($result);

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    /**根据当前人uid获取被考核人列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function findreviewedpeoplelist(Request $request){
        try {

            $uid = $request->param('uid');
            $orgid_input = $request->param('orgid');
            $ProjectPerOrgPeople = new ProjectPerOrgPeopleModel();
            $peopleinfo = $ProjectPerOrgPeople->where('uid','=',$uid)->select();

            $kp = 0;
            if($peopleinfo != null){
                $peopleinfoArr = $peopleinfo->toArray();
                if(count($peopleinfoArr) == 1){
                    $kp = $peopleinfoArr[0]['kp'];
                }else{
                    foreach ($peopleinfoArr as $v){
                        if($v['kp']){
                            $kp = 1;
                            break;
                        }
                    }
                }
            }

            if($kp){

                $orgid = "";
                if(count($peopleinfoArr) == 1){
                    $orgid = $peopleinfoArr[0]['orgid'];
                }else{
                    foreach ($peopleinfoArr as $v){
                        if($v['kp']){
                            $orgid = $orgid.",".$v['orgid'];
                            $orgid = ltrim($orgid,',');
                        }
                    }
                }
                $ProjectPerOrgModel = new ProjectPerOrgModel();
                //$this->findOrglistIteraction($ProjectPerOrgModel,$orgid,$uid);
                $this->findOrglistIteraction($ProjectPerOrgModel,$orgid,false,"");
                global  $org_global;
                $orglist = $org_global;
                //构造查询字符串
                $orgArr = "{$orgid}";
                if($orglist){
                    foreach ($orglist as $o){
                        $orgArr = $orgArr.",".$o['id'];
                    }
                }

                if($orgid_input){
                       $ishave = strstr($orgArr, $orgid_input);
                        if($ishave){
                            $orgArr = $orgid_input;
                        }else{
                            $orgArr = "";
                        }

                }

                $reviewedlist = $ProjectPerOrgPeople->where('uid','NOT IN',$uid)
                    ->where('is_reiviewed','=',1)
                    ->where('orgid','IN',$orgArr)
                    ->where('is_outer','<>',1)
                    ->select()->toArray();
                $sql = $ProjectPerOrgPeople->getLastSql();

                if($peopleinfo){
                    $error = ["status"=>true,"msg"=>"获取列表成功！","data"=>$reviewedlist];
                    return json($error);
                }else{
                    $error = ["status"=>false,"msg"=>"获取列表失败！","data"=>[]];
                    return json($error);
                }

            }else{
                $error = ["status"=>false,"msg"=>"获取列表失败！","data"=>[]];
                return json($error);
            }

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    /**
     * 组织查询的迭代
     * @param $ProjectPerOrgModel
     * @param $orgid
     * @param $orgLock_count
     * @return array|\think\response\Json
     */
    private function findOrglistIteraction($ProjectPerOrgModel,$orgid,$orgLock_count,$month){
        try {

            global  $org_global;
            if(!is_numeric($orgid) && (strpos($orgid, ',') !== false)){
              $orgidArr = explode(',',$orgid);
                foreach ($orgidArr as $vv){
                    if(!$orgLock_count){
                        $orglist_d = $ProjectPerOrgModel->where('pid',$vv)->select()->toArray();
                    }else{
                        $orglist_d = $ProjectPerOrgModel->where('pid',$vv)->where('month','like',$month)->select()->toArray();
                    }

                    foreach($orglist_d as $v){
                        $org_global[] = $v;
                        $this->findOrglistIteraction($ProjectPerOrgModel,$v['id'],$orgLock_count,$month);
                    }
                }
            }else{

                if(!$orgLock_count){
                    $orglist_d = $ProjectPerOrgModel->where('pid',$orgid)->select()->toArray();
                }else{
                    $orglist_d = $ProjectPerOrgModel->where('pid',$orgid)->where('month','like',$month)->select()->toArray();
                }
                foreach($orglist_d as $v){
                    $org_global[] = $v;
                    $this->findOrglistIteraction($ProjectPerOrgModel,$v['id'],$orgLock_count,$month);
                }
            }

            return true;

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    /**
     * 向上查找某人的组织树
     * @param $ProjectPerOrgModel
     * @param $orgid
     * @return \think\response\Json
     */
    private function findOrgListUpIteraction($ProjectPerOrgModel,$orgid){
        try {

            global $org_global_up;
            $orglist = $ProjectPerOrgModel->where('id',$orgid)->find();
            if($orglist['id']){
                $org_global_up[] = $orglist['id'];
            }
            if($orglist){
                $orglist = $orglist->toArray();
                $this->findOrgListUpIteraction($ProjectPerOrgModel,$orglist['pid']);
            }
            return true;

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }
    /**
     * 找到当前考核人的考核单
     * @param Request $request
     * @return \think\response\Json
     */
    public function findreviewedpeoplefrom(Request $request){
        try {

            $orgid = $request->param('orgid');
            $month = $request->param('month');
            if(!$month){
                $month = strtotime(date('Y-m',strtotime("-1 month")));
            }else{
                $month = strtotime($month);
            }

            $ProjectPerOrgModel = new ProjectPerOrgModel();
            $this->findOrgListUpIteraction($ProjectPerOrgModel,$orgid);
            global $org_global_up;

            $orgArr_tmp = "";
            if($org_global_up){
                $orgArr_tmp = implode(',',$org_global_up);
            }
            $ProjectPerOrgPeople = new ProjectPerOrgPeopleModel();
            $peopleinfo_tmp = $ProjectPerOrgPeople->where('id','=',$request->param('performance_id'))->find()->toArray();
            $peopleinfo = $ProjectPerOrgPeople->field('id,uid,orgid,name,kp')->where('uid','=',$peopleinfo_tmp['uid'])
                                              ->where('orgid','IN',$orgArr_tmp)
                                              ->where('kp','>','0')
                                              ->select();

            $sql_m =  $ProjectPerOrgPeople->getLastSql();

            //加入当前传入的orgid没有找到相关的人，那么去查找上级组织是否有这个人
            if($peopleinfo){
                $peopleinfo = a_array_unique($peopleinfo->toArray());
            }
            $peopleinfo_arr = "";
            if($peopleinfo){
                foreach ($peopleinfo as $o){
                    $peopleinfo_arr = $peopleinfo_arr.$o['kp'].',';
                }
                $peopleinfo_arr = rtrim($peopleinfo_arr,',');
            }

            $sql = $ProjectPerOrgPeople->getLastSql();

            if($peopleinfo){

                $orgArr_tmp = rtrim($orgArr_tmp,',');
                $orgArr_t = $orgArr_tmp.",0"; //把未设置部组的记录也查询出来
                $ProjectReviewResultModel = new ProjectReviewResultModel;
                $reviewlist = $ProjectReviewResultModel->alias('rw')
                    ->field('rw.id,s.name,s.weight,rw.score,s.type,FROM_UNIXTIME(rw.month,\'%Y-%m\') as month')
                    ->leftjoin('ProjectPerformanceSpot s','rw.spot_id = s.id')
                    ->leftjoin('ProjectPerformanceContent c','s.content_id = c.id')
                    ->where('rw.month','=',$month)
                    ->where('s.orgid','IN',$orgArr_t)
                    ->where('rw.uid','=',$request->param('uid'))
                    ->where('rw.class_id','IN',$peopleinfo_arr)
                    ->select()->toArray();

                $sql = $ProjectReviewResultModel->getLastSql();

                if($reviewlist){
                    $error = ["status"=>true,"msg"=>"获取列表成功！","data"=>$reviewlist];
                    return json($error);
                }else{
                    $error = ["status"=>false,"msg"=>"获取列表失败！","data"=>""];
                    return json($error);
                }

            }else{
                $error = ["status"=>false,"msg"=>"获取列表失败！","data"=>""];
                return json($error);
            }

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    /**
     * 设置被考核人当前考核项的分值
     * @param Request $request
     * @return \think\response\Json
     */
    public function setSpotScore(Request $request){
        try {
            $ProjectReviewResultModel = new ProjectReviewResultModel();
            $data['score'] = $request->param('score');
            $res = $ProjectReviewResultModel->where('id','=',$request->param('id'))->save($data);
            if($res!==false){
                $error = ["status"=>true,"msg"=>"修改成功！"];
                return json($error);
            }else{
                $error = ["status"=>false,"msg"=>"修改失败！"];
                return json($error);
            }
        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    /**
     * 绩效
     * @param  uid 当前人uid
     * @param Request $request
     * @return \think\response\Json
     */
    public function scoreSort(Request $request){
        try {

            $uid = $request->param('uid');
            $month = strtotime($request->param('month'));

            $ProjectPerOrgPeopleModel = new ProjectPerOrgPeopleModel();
            $userinfo = $ProjectPerOrgPeopleModel->where('id','=',$uid)
                ->find();

            if($userinfo){
                $userinfo = $userinfo->toArray();
                $userinfo = $ProjectPerOrgPeopleModel->where('uid','=',$userinfo['uid'])
                                                     ->where('is_outer','=',0)
                                                     ->find();
                $uid = $userinfo['id'];
            }

            //根据这些部门去查询评分记录并汇总
            $ProjectReviewResultModel = new ProjectReviewResultModel;
            $ProjectPerformanceClassModel = new ProjectPerformanceClassModel;
            $ProjectPerformanceSpotModel = new ProjectPerformanceSpotModel;
            $weight_quality = $ProjectPerformanceClassModel->where('id','=',2)->find()->toArray(); //取质量分类得权重
            $spot_quality = $ProjectPerformanceSpotModel->where('weight','>',0)->select();//取考核标准得权重，有权重值的，按照权重值算出来的分数，加到总分里边
            $spot_quality_arr = "";
            foreach ($spot_quality as $v){
                $spot_quality_arr = $spot_quality_arr.$v['id'].',';
            }
            $spot_quality_arr = rtrim($spot_quality_arr, ",");
            $reviewResultList_quality = $ProjectReviewResultModel->alias('rw')
                 ->field('p.name,rw.uid,((sum(rw.score)+100)*'.($weight_quality["weight"]/100).') as total_score')
                 ->join('ProjectPerOrgPeople p','rw.uid = p.id')
                 ->where('rw.uid','=',$uid)
                 ->where('rw.month','=',$month)
                 ->where('spot_id','NOT IN',"$spot_quality_arr")
                 ->where('class_id','=',2)
                 ->group('rw.uid')
                 ->select()->toArray(); //不包括考核标准设置了权重值的

            $reviewResultList_weight_quality= $ProjectReviewResultModel->alias('rw')
                ->field('p.name,rw.uid,(sum(rw.score*(weight/100))) as total_score')
                ->join('ProjectPerOrgPeople p','rw.uid = p.id')
                ->join('project_performance_spot s','rw.spot_id = s.id')
                ->where('rw.month','=',$month)
                ->where('rw.uid','=',$uid)
                ->where('spot_id','IN',"$spot_quality_arr")
                ->where('rw.class_id','=',2)
                ->group('rw.uid')
                ->select()->toArray(); //只包含考核标准设置了权重值的

            //return $ProjectReviewResultModel->getLastSql();

            $weight_normal = $ProjectPerformanceClassModel->where('id','=',1)->find()->toArray();
            $reviewResultList_normal = $ProjectReviewResultModel->alias('rw')
                ->field('p.name,rw.uid,(sum(rw.score)*'.($weight_normal["weight"]/100).') as total_score')
                ->join('ProjectPerOrgPeople p','rw.uid = p.id')
                ->where('rw.month','=',$month)
                ->where('rw.uid','=',$uid)
                ->where('class_id','=',1)
                ->group('rw.uid')
                ->select()->toArray(); //不包括考核标准设置了权重值的

            if($reviewResultList_normal){

                //把质量分加入到日常分里去
                $i=0;
                foreach($reviewResultList_normal as $key=>$vo){

                    foreach ($reviewResultList_quality as $k=>$v){
                         if($v['uid'] == $vo['uid']){
                             $reviewResultList_normal[$i]['total_score'] = $reviewResultList_normal[$i]['total_score']+$v['total_score'];
                         }
                    }
                    $i++;

                }

                //把附加费加进去
                $i=0;
                foreach($reviewResultList_normal as $key=>$vo){

                    foreach ($reviewResultList_weight_quality as $k=>$v){
                        if($v['uid'] == $vo['uid']){
                            $reviewResultList_normal[$i]['total_score'] = $reviewResultList_normal[$i]['total_score']+$v['total_score'];
                        }
                    }
                    $i++;

                }


            }

            if($reviewResultList_normal){
                $reviewResultList_normal_result = arraySort($reviewResultList_normal, 'total_score', SORT_DESC);
                $result = ['status'=>true,'msg'=>'获取数据成功！','data'=>$reviewResultList_normal_result];
                return json($result);
            }else{
                $result = ['status'=>false,'msg'=>'获取数据失败！','data'=>''];
                return json($result);
            }


        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    /**
     * 绩效排名迭代
     * @param $ProjectPerOrgModel
     * @param $orgid
     */
    private function scoresortIteraction($ProjectPerOrgModel,$orgid,$orginfo_tmp_count,$month){
        global $score_orgid;
        if(!$orginfo_tmp_count){
            $orginfo = $ProjectPerOrgModel->where('id','=',$orgid)->find();
        }else{
            $orginfo = $ProjectPerOrgModel->where('id','=',$orgid)->where('month','like',$month)->find();
        }

        if($orginfo['pid'] && $orginfo['depart_spot']!=1) {
            $score_orgid = $orginfo['pid'];
            $this->scoresortIteraction($ProjectPerOrgModel,$orginfo['pid'],$orginfo_tmp_count,$month);
        }
        if(!$score_orgid){
            $score_orgid = $orgid;
        }
    }

    /**
     * 查询项目经理的分数
     * @param Request $request
     * @return \think\response\Json
     */
    public function selectLevlScore(Request $request){
        try {

            $uid = $request->param('uid');
            //先查询下改用户是不是项目经理
            $ProjectPerOrgPeopleModel = new ProjectPerOrgPeopleModel;
            $orgPeopleInfo = $ProjectPerOrgPeopleModel->where('uid','=',$uid)->find();
            $orgPeopleInfo_uid = "";
            if($orgPeopleInfo){
                $orgPeopleInfo = $orgPeopleInfo->toArray();
                $orgPeopleInfo_uid = $orgPeopleInfo['uid'];
            }

            //查询项目经理
            $ProjectInfoModel = new ProjectInfoModel;
            $projectList = $ProjectInfoModel->where('project_pm','=',$orgPeopleInfo_uid)
                ->where('is_check','=',1)
                ->select();

            if($projectList){
                $projectList = $projectList->toArray();
            }

            $total_score = 0;
            if(is_array($projectList)){
                $ProjectLevel = new ProjectLevel;
                foreach ($projectList as $vo){
                    $info = $ProjectLevel->where('name','LIKE',$vo['project_level'])->find();
                    if($info){
                        $info = $info->toArray();
                    }
                    $total_score = $total_score+$info['score'];
                }
            }

            if($total_score){
                $result = ['status'=>true,'msg'=>'获取数据成功','data'=>$total_score];
                return json($result);
            }else{
                $result = ['status'=>false,'msg'=>'获取数据失败','data'=>0];
                return json($result);
            }
        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    /**
     * 根据用户id获取项目考核成绩总分
     * @param Request $request
     * @return \think\response\Json
     */
    public function projectTeamReviewScore(Request $request){
        try {

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }
    /**
     * 根据项目id查询项目成员列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function projectTeamList(Request $request){
        try {
            $cru_time = strtotime(date('Y-m'));
            $next_time = strtotime("+1 months", $cru_time);
            //return date('Y-m',$next_time);
            $project_id = $request->param('project_id');
            $ProjectTeaminfoModel = new ProjectTeaminfoModel;
            $teamlist = $ProjectTeaminfoModel->alias('t')
                       ->field('t.id,t.uid,t.project_id,t.en_name,t.zn_name,t.create_time,t.status')
                       ->join('user u','t.uid=u.id')
                       //->where('create_time','<',$next_time)
                       //->where('create_time','>=',$cru_time)
                       ->where('status','=',1)
                       ->where('u.deleted','=',0)
                       ->where('project_id','=',$project_id)
                       ->select();
            if($teamlist){
                $teamlist = $teamlist->toArray();
                $result = ['status'=>true,'msg'=>'获取数据成功！','data'=>$teamlist];
            }else{
                $result = ['status'=>false,'msg'=>'获取数据失败！','data'=>''];
            }
            return json($result);
        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    /**
     * 团队成员考核绩效分列表（带分页）
     * @param Request $request
     * @return \think\response\Json
     */
    public function projectTeamReviewList(Request $request){
        try {
            $id = $request->param('uid');
            //根据传入的id值去团队表里边去取出uid
            $projectteamInfo = new ProjectTeaminfoModel();
            $teamInfo = $projectteamInfo->where('id','=',$id)->find();
            $uid = $teamInfo['uid'];

            $project_id = $request->param('project_id');
            $page = $request->param('page');
            $pagesize = $request->param('pagesize');
            //$month = strtotime(date('Y-m'));
            $ProjectTeamScoreModel = new ProjectTeamScoreModel();
            $list = $ProjectTeamScoreModel->alias('s')
                ->field('*,FROM_UNIXTIME(s.month,\'%Y-%m\') as month')
                ->where('uid','=',$uid)
                ->where('project_id','=',$project_id)
                //->where('month','=',$month)
                ->order('month desc')
                ->paginate([
                    'list_rows'=> $pagesize,
                    'var_page' => 'page',
                    'page'=>$page
                ]);
            if($list){
                $result = ["status"=>true,"msg"=>"获取列表成功！","data"=>$list];
            }else{
                $result = ["status"=>false,"msg"=>"获取列表失败！"];
            }
            return json($result);
        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    /**
     * 考核成绩添加
     * @param Request $request
     * @return \think\response\Json
     */
    public function projectTeamReviewAdd(Request $request){
        try {

            $id = $request->param('uid');
            $month = $request->param('month');
            if(!$month){
                $month = strtotime(date('Y-m'));
            }else{
                $month = strtotime(date('Y-m',strtotime($month)));
            }

            //根据传入的id值去团队表里边去取出uid
            $projectteamInfo = new ProjectTeaminfoModel();
            $ProjectTeamScoreModel = new ProjectTeamScoreModel;

            $teamInfo = $projectteamInfo->where('id','=',$id)->find();
            $uid = $teamInfo['uid'];

            $project_id = $request->param('project_id');
            $score = $request->param('score');
 
            $w = [];
            $w[] = ['l.min_score','<=',$score];
            $w[] = ['l.max_score','>=',$score];
            $w[] = ['i.id','=',$project_id];
            $ProjectInfoModel = new ProjectInfoModel();
            $scoreInfo_t = $ProjectInfoModel->alias('i')
                ->join('project_level l','i.project_level = l.name')
                ->where($w)
                ->find();
         
            if(!$scoreInfo_t){    
                
                //查询当前项目的打分范围
                 $w = [];
                 $w[] = ['i.id','=',$project_id];
                 $scoreInfo = $ProjectInfoModel->alias('i')
                     ->join('project_level l','i.project_level = l.name')
                     ->where($w)
                     ->find();

                $scoreInfo = $scoreInfo->toArray();
                $result = ['status'=>false,'msg'=>'不能超过分数范围：'.$scoreInfo['min_score'].'~~'.$scoreInfo['max_score']];
                return $result;
            }

            $data['uid'] = $uid;
            $data['project_id'] = $project_id;
            $data['month'] = $month;
            $data['score'] = $score;
            $data['status'] = 1;
            $data['create_time'] = time();


            $res = $ProjectTeamScoreModel->insertGetId($data);
            if($res){
                $result = ['status'=>true,'msg'=>'添加成功！','re_id'=>$res];
            }else{
                $result = ['status'=>false,'msg'=>'添加失败！'];
            }
            return $result;

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    /**
     * 考核成绩保存
     * @param Request $request
     * @return \think\response\Json
     */
    public function projectTeamReviewSave(Request $request){
        try {

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    /**
     * 考核成绩删除
     * @param Request $request
     * @return \think\response\Json
     */
    public function projectTeamReviewDel(Request $request){
        try {
            $id = $request->param('id');
            $ProjectTeamScoreModel = new ProjectTeamScoreModel;
            $res = $ProjectTeamScoreModel->where('id','=',$id)->delete();
            if($res){
                $result = ['status'=>true,'msg'=>'删除成功！'];
            }else{
                $result = ['status'=>false,'msg'=>'删除失败！'];
            }
            return $result;
        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    /**
     * 查询项目成员的考核分数
     * @param Request $request
     * @return \think\response\Json
     *
     */
    public function selectProjectTeamersScore(Request $request){
        try {

            $uid = $request->param('uid');
            $month = strtotime($request->param('month'));
            $ProjectTeamScoreModel = new ProjectTeamScoreModel;
            $projectInfo = $ProjectTeamScoreModel->alias('s')
                                                 ->field('u.realname,p.project_name,p.project_level,s.score,s.create_time,FROM_UNIXTIME(s.month,\'%Y-%m\') as month')
                                                 ->leftjoin('user u','s.uid = u.id')
                                                 ->leftjoin('project_info p','s.project_id = p.id')
                                                 ->where('s.uid','=',$uid)
                                                 ->where('s.month','=',$month)->select()->toArray();
            $total_score = $ProjectTeamScoreModel->where('uid','=',$uid)->where('month','=',$month)->sum('score');
            if($projectInfo){
                $tmp['data'] = $projectInfo;
                $tmp['total_score'] = $total_score;
                $result = ['status'=>true,'msg'=>'获取成功！','data'=>$tmp];
            }else{
                $result = ['status'=>false,'msg'=>'获取失败！'];
            }
            return $result;

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

    public function getCreateResultTimeList(){

    }

    /**
     * 获取个人考核列表
     * @param Request $request
     * @return array|\think\response\Json
     */
    public function getPeopleReviewResultList(Request $request){
        try {

            $uid = $request->param('uid');
            $month = strtotime($request->param('month'));
            $ProjectReviewResultModel = new ProjectReviewResultModel();
            $list = $ProjectReviewResultModel->alias('r')
                ->field('s.name,r.score,FROM_UNIXTIME(r.month,\'%Y-%m\') as month')
                ->leftjoin('project_performance_spot s','r.spot_id = s.id')
                ->where('r.uid','=',$uid)
                ->where('r.month','=',$month)
                ->select();

            $sql = $ProjectReviewResultModel->getLastSql();
            if($list){
                $tmp['data'] = $list->toArray();;
                $result = ['status'=>true,'msg'=>'获取成功！','data'=>$tmp];
            }else{
                $result = ['status'=>false,'msg'=>'获取失败！'];
            }
            return json($result);

        } catch (\Exception $e) {
            $error = ["status"=>false,"msg"=>$e->getMessage(),"code"=>$e->getCode()];
            return json($error);
        }
    }

}
